package com.downrice.controller;


import com.downrice.dao.*;
import com.downrice.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lxiafan on 2017/1/9.
 */
@Controller
public class mainController {
    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    NoticeRepository noticeRepository;
    @Autowired
    PersonRepository personRepository;
    @Autowired
    NoteRepository noteRepository;

    static UserDetails userDetails = null;

    Sort s=new Sort(Sort.Direction.DESC, "id");// 根据id倒叙

   @RequestMapping(value={"/","/home"})
    public String home(Model model){

        List<Notice> notices = noticeRepository.findAll(s);

        msg ms =  new msg("测试标题","测试内容","额外信息，只对管理员显示");

        model.addAttribute("msg", ms);
        model.addAttribute("notices", notices);
        return "home";
    }

    @RequestMapping(value="/reg")
    public String reg(){
        return "reg";
    }
    @RequestMapping(value="/reg_sub")
    public String reg_sub(Model model,
                      @RequestParam(value = "username")String username,
                      @RequestParam(value = "password")String password,
                      @RequestParam(value = "email")String mail,
                      @RequestParam(value = "sex")String sex){
        System.out.println("user");
        List<Role> roles = roleRepository.findByName("ROLE_USER");
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        password = passwordEncoder.encode(password);
        User user = new User(username, password, sex, mail, roles);
        userRepository.save(user);
        return "login";
    }

    @RequestMapping(value="/roles")
    public String roles(Model model){
        Page<Role> page = roleRepository.findAll(new PageRequest(0,5));
        List<Notice> notices = noticeRepository.findAll(s);
        model.addAttribute("datas", page);
        model.addAttribute("notices", notices);
        return "roles";
    }
    @RequestMapping(value="/addRole")
    public String addRole(Model model, @RequestParam(value="roleName") String roleName){
        roleName = "ROLE_" + roleName;
        Role role = new Role(roleName);
        try {
            roleRepository.save(role);
        }catch (Exception e){
            return  "roles?error";
        }
        return  roles(model);
    }
    @RequestMapping(value="/editRoles")
    public void editRoles(@RequestParam(value="rid") String rid,
    @RequestParam(value="uid") String uid, @RequestParam(value="state") String state
    ){
        User user = userRepository.findOne(Long.parseLong(uid));
        Role role = roleRepository.findOne(Long.parseLong(rid));
        if(state.equals("true") || state=="true"){
            // 添加角色
            user.getRoles().add(role);
        }else {
            // 移除角色
            user.getRoles().remove(role);
        }
        userRepository.save(user);
    }

    @RequestMapping(value="/assign")
    public String assign(Model model){
        //Page<Role> page = roleRepository.findAll(new PageRequest(0,5));
        Page<User> page = userRepository.findAll(new PageRequest(0,5));
        List<Role> roles = roleRepository.findAll();
        List<Notice> notices = noticeRepository.findAll(s);
        model.addAttribute("datas", page);
        model.addAttribute("roles", roles);
        model.addAttribute("notices", notices);
        return "assign";
    }

    @RequestMapping(value="/notices")
    public String notices(Model model){
        Page<Notice> page = noticeRepository.findAll(new PageRequest(0,5, s));
        List<Notice> notices = noticeRepository.findAll(s);
        model.addAttribute("datas", page);
        model.addAttribute("notices", notices);
        return "notices";
    }
    @RequestMapping(value="/addNotice")
    public String addNotice(Model model,@RequestParam(value="content") String content){
        Date dt=new Date();
        SimpleDateFormat matter1=new SimpleDateFormat("yyyy-MM-dd");
        Notice notice = new Notice("admin",matter1.format(dt),content);
        System.out.println("notice");
        try {
            noticeRepository.save(notice);
        }catch (Exception e){
            return  "notices?error";
        }
        return  notices(model);
    }

    @RequestMapping(value="/persons")
    public String persons(Model model){
        Page<Person> page = personRepository.findAll(new PageRequest(0,5));
        List<Notice> notices = noticeRepository.findAll(s);
        List<User> users = userRepository.findAll();
        List<String> names = new ArrayList<String>();
        for (User user : users){
            names.add(user.getUsername());
        }
        model.addAttribute("names", names);
        model.addAttribute("datas", page);
        model.addAttribute("notices", notices);
        return "persons";
    }

    @RequestMapping(value = "/addPerson")
    public String addPerson(Model model, @RequestParam(value = "name") String name,
                            @RequestParam(value = "sex") String sex, @RequestParam(value = "birthday") String birthday,
                            @RequestParam(value = "phone") String phone, @RequestParam(value = "mail") String mail,
                            @RequestParam(value = "idnum") String idnum){
        Person person = new Person(name, sex, birthday, mail, phone, idnum);
        try {
            personRepository.save(person);
        }catch (Exception e){
            return  "persons?error";
        }
        return persons(model);
    }

    @RequestMapping(value = "/getPerson")
    public void getPerson(PrintWriter out, @RequestParam(value = "id") String id){
        Long pid = Long.parseLong(id);
        Person person = personRepository.findOne(pid);
        System.out.println(person.getName());
        ObjectMapper mapper = new ObjectMapper();
        String jsonObject = null;
        try {
            jsonObject = mapper.writeValueAsString(person);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        out.write(jsonObject);
    }

    @RequestMapping(value = "/editPerson")
    public void editPerson(Model model,@RequestParam(value = "id") String pid,@RequestParam(value = "name") String name,
                           @RequestParam(value = "sex") String sex, @RequestParam(value = "birthday") String birthday,
                           @RequestParam(value = "phone") String phone, @RequestParam(value = "mail") String mail,
                           @RequestParam(value = "idnum") String idnum){
        Long id = Long.parseLong(pid);
        Person person = personRepository.findOne(id);
        person.setName(name);
        person.setBirthday(birthday);
        person.setMail(mail);
        person.setSex(sex);
        person.setIdnum(idnum);
        person.setPhone(phone);
        personRepository.save(person);
    }

    @RequestMapping(value = "/setUser")
    public String getUsers(Model model, @RequestParam(value = "id") String pid,
                           @RequestParam(value = "username") String username){
        Long id = Long.parseLong(pid);
        Person person = personRepository.findOne(id);
        User user = userRepository.findByUsername(username);
        person.setUser(user);
        user.setPerson(person);
        //personRepository.save(person);
        userRepository.save(user);// 控制权在user，所以更新user即可
        return persons(model);
    }

    @RequestMapping(value = "/notes")
    public String notes(Model model){
        userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Person person = userRepository.findByUsername(userDetails.getUsername()).getPerson();
        List<Note> notes = noteRepository.findByPersonOrderByTimeDesc(person);
        List<Notice> notices = noticeRepository.findAll(s);
        model.addAttribute("notices", notices);
        model.addAttribute("notes", notes);
        model.addAttribute("person", person);
        return "notes";
    }

    @RequestMapping(value = "/addNote")
    public String addNote(Model model, @RequestParam(value = "title") String title,
                          @RequestParam(value = "content") String content,@RequestParam(value = "time") String time){
        Note note = new Note(title, time, content);
        Person person = userRepository.findByUsername(userDetails.getUsername()).getPerson();
        System.out.println(person.getNotes().size()+ "$%$%$%$$$$$$$$$$$$$");
        if(person != null){
            //person = personRepository.findOne(person.getId());
            note.setPerson(person);
            person.getNotes().add(note);
            //personRepository.save(person);
            noteRepository.save(note);
            //personRepository.save(person);
        }
        return notes(model);
    }

    @RequestMapping(value="/setNoteState")
    public void setNoteState(Model model, @RequestParam(value="nid") String nid, @RequestParam(value="nstate") String nstate
    ){
        Long id = Long.parseLong(nid);
        Boolean state = Boolean.parseBoolean(nstate);
        state = !state;
        Note note = noteRepository.findOne(id);
        note.setState(state);
        noteRepository.save(note);
    }
    @RequestMapping(value="/delNote")
    public void delNote(Model model, @RequestParam(value="nid") String nid){
        Long id = Long.parseLong(nid);
        noteRepository.delete(id);
    }
}
